﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2022   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 机器名称：DESKTOP-UL84BU5
 * 公司名称：
 * 命名空间：KingerRobot.WanliWMS.SpiService.Services.Setting
 * 唯一标识：a3991923-c0f3-4bde-a484-2d005509bad5
 * 文件名：BSettingImpl
 * 当前用户域：DESKTOP-UL84BU5
 * 
 * 创建者：zzl
 * 电子邮箱：1003590782@qq.com
 * 创建时间：2022/7/4 15:42:44
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>

using KingerRobot.MexicoSailunMDC.Dao;
//using KingerRobot.MexicoSailunMES.Dao;
using KingerRobot.MexicoSailunMES.Spi.DTO;
using KingerRobot.MexicoSailunMES.Spi;
using System;
using System.ServiceModel.Channels;
using System.Threading.Tasks;

namespace KingerRobot.MexicoSailunWMS.SpiService;
//WMS.Task
public class BTaskImpl : ITaskService
{
    private readonly static ITask _Task = new BTask();
    private readonly static ITaskCmd _TaskCmd = new BTaskCmd();
    private readonly static IRcsEquip _RcsEquip = new BRcsEquip();
    private readonly static IWmsOutOrderMaster _WmsOutOrderMaster = new BWmsOutOrderMaster();
    private readonly static IWmsOutOrderSummary _WmsOutOrderSummary = new BWmsOutOrderSummary();
    private readonly static IRcsLocation _RcsLocation = new BRcsLocation();
    private readonly static IWcsEquipLoc _WcsEquipLoc = new BWcsEquipLoc();
    private readonly static IWcsLocSku _WcsLocSku = new BWcsLocSku();
    private readonly static ICuringManageService _CuringManageService = new BCuringManageImpl();
    private readonly static IWcsAsrsNetOutPut _WcsAsrsNetOutPut = new BWcsAsrsNetOutPut();
    private readonly static IWcsNetInCuring _WcsNetInCuring = new BWcsNetInCuring();
    private readonly static IBakWcsTask _BakWcsTask = new BBakWcsTask();
    private readonly static IProdProduct _ProdProduct = new BProdProduct();
    private readonly static IMesRpc _MesRpc = new BMesRpc();
    private readonly static IWcsAsrsCrnAbnormalInput _WcsAsrsCrnAbnormalInput = new BWcsAsrsCrnAbnormalInput();
    private readonly static IWcsScanner _WcsScanner = new BWcsScanner();
    private readonly static IMesProduct _MesProduct = new BMesProduct();
    private readonly static IRcsEquipCuring _RcsEquipCuring = new BRcsEquipCuring();
    private readonly static IProdMaterial _ProdMaterial = new BProdMaterial();

    public List<TaskType> GetTaskTypes()
    {
        List<TaskType> list = new List<TaskType>();//定义一个list
        foreach (var enumame in Enum.GetValues(typeof(EnumTaskType)))
        {
            TaskType m = new TaskType();
            m.TypeKey = Convert.ToInt32(enumame);
            m.TypeDesc = EnumExtension.GetDescription((EnumTaskType)enumame);
            list.Add(m);
        }
        return list;
    }

    public List<ComboEquipBean> GetComboEquips()
    {
        List<ComboEquipBean> list = new List<ComboEquipBean>();

        List<long?> equipTypes = new List<long?>();
        foreach (var enumame in Enum.GetValues(typeof(EnumCodeEquipType)))
        {
            equipTypes.Add(Convert.ToInt32(enumame));
        }
        list = _RcsEquip.GetRcsEquipByType(equipTypes).Select(s => new ComboEquipBean { Id = s.Id, Name = s.EquipName }).OrderBy(o => o.Id).ToList();
        return list;
    }

    public List<TaskBean> GetTaskList(TaskParm taskinfo)
    {
        var taskList = _Task.GetVTasksOrderBy(taskinfo?.OrderByType, taskinfo?.OrderByName);  //_Task.GetVTasks();
        var taskNo = 0;
        if (!string.IsNullOrWhiteSpace(taskinfo.TaskNo))
        {
            taskNo = Convert.ToInt32(taskinfo.TaskNo);
        }
        if (taskNo != 0)
        {
            taskList = taskList.Where(t => t.TaskNo.ToString().Contains(taskinfo.TaskNo.ToString())).ToList();
        }
        if (!string.IsNullOrWhiteSpace(taskinfo.TaskType))
        {
            taskList = taskList.Where(t => t.TaskType == Convert.ToInt32(taskinfo.TaskType)).ToList();
        }
        //if (!string.IsNullOrWhiteSpace(taskinfo.EquipId))
        //{
        //    taskList = taskList.Where(t => t.CurrentEquipId == Convert.ToInt32(taskinfo.EquipId)).ToList();
        //}
        if (!string.IsNullOrWhiteSpace(taskinfo.EquipName))
        {
            taskList = taskList.Where(t => t.CurrentEquip?.StartsWith(taskinfo.EquipName) ?? false).ToList();
        }
        if (!string.IsNullOrWhiteSpace(taskinfo.BarCode))
        {
            taskList = taskList.Where(t => t.ProductCode != null && t.ProductCode.Contains(taskinfo.BarCode)).ToList();
        }
        //指定时间段
        if (taskinfo.StartTime is not null && taskinfo.EndTime is not null)
        {
            taskList = taskList.Where(f => f.createTime >= taskinfo.StartTime && f.createTime <= taskinfo.EndTime).ToList();
        }
        if (!string.IsNullOrWhiteSpace(taskinfo.TargetLoc))
        {
            taskList = taskList.Where(t => t.TargetLoc != null && t.TargetLoc.Contains(taskinfo.TargetLoc)).ToList();
        }

        return taskList.Select(f => new TaskBean
        {
            cmdExcuteTime = f.CmdExcuteTime.GetValueOrDefault(),
            cmdTime = f.CmdTime.GetValueOrDefault(),
            createTime = f.createTime.GetValueOrDefault(),
            CurrentLoc = f.CurrentLoc,
            StartEquip = f.StartEquip,
            StartLoc = f.StartLoc,
            TargetLoc = f.TargetLoc,
            TaskNo = f.TaskNo.GetValueOrDefault(),
            TaskStatus = f.TaskStatus.GetValueOrDefault(),
            TaskType = f.TaskType.GetValueOrDefault(),
            TaskGroup = f.TaskGroup ?? 0,
            CurrentEquip = f.CurrentEquip,
            ProductCode = f.ProductCode,
            TaskTypeDesc = EnumExtension.GetDescription((EnumTaskType)Enum.Parse(typeof(EnumTaskType), f.TaskType.ToString())),
            TaskStatusDesc = EnumExtension.GetDescription((EnumTaskStatus)Enum.Parse(typeof(EnumTaskStatus), f.TaskStatus.ToString())),
        }).OrderBy(o => o.createTime).ToList();
    }

    #region 任务完成
    [OperationLog("任务完成")]
    public int FinishTask(TaskOperParm parm, long userId, string userName, string clientHost)
    {
        var task = _Task.GetTaskByTaskNo(parm.TaskNo);
        if (task == null) return 0;
        int result;
        // 修改备注
        _Task.UpdateTaskReamrkByTaskId(task.Id.GetValueOrDefault(), $"{task.RemarkMemo},人工完成");

        switch (task.TaskType)
        {
            case (int)EnumTaskType.Warehousing:
                result = WarehousingTaskFinish(task);

                break;

            case (int)EnumTaskType.Exwarehouse:
                result = 0;// ExwarehouseTaskFinish(task);

                break;

            case (int)EnumTaskType.Transportation:
                result = 0;// TransportationTaskFinish(task);

                break;

            case (int)EnumTaskType.EMS:
                result = EmsTaskFinish(task);
                break;

            default:
                result = Abnormal(task);
                break;
        }
        return result;
    }

    // 输送任务完成 [完成删除任务、指令、删除绑定]
    public int TransportationTaskFinish(POWcsTask task)
    {
        var taskId = task?.Id ?? 0;
        // 修改状态
        _Task.UpdateTaskAndCmdStatusForManualEnd(task.TargetLoc.GetValueOrDefault(), taskId, (int)EnumTaskStatus.Finish);
        // 备份删除
        _Task.BakAndDeleteTaskAndCmd(taskId);
        // 清空绑定
        _WcsLocSku.DeleteWcsLocSkuBySkuId(taskId);
        return 1;
    }

    // 入库任务完成 [完成删除任务、指令、绑定目标位]
    public int WarehousingTaskFinish(POWcsTask task)
    {
        var taskId = task?.Id ?? 0;
        // 修改状态
        _Task.UpdateTaskAndCmdStatusForManualEnd(task.TargetLoc.GetValueOrDefault(), taskId, (int)EnumTaskStatus.Finish);
        // 备份删除
        _Task.BakAndDeleteTaskAndCmd(taskId);
        // 修改货位标识
        _RcsLocation.UpdateLocationAndWcsLocWithSkuId(task.SkuId, 0, task.TargetLoc, true);


        return 1;
    }
    // 出库任务完成 [完成删除任务、指令、绑定目标位]
    public int ExwarehouseTaskFinish(POWcsTask task)
    {
        var taskId = task?.Id ?? 0;
        var taskNo = task?.TaskNo ?? 0;
        var taskCmd = _TaskCmd.GetExecutedTaskCmdByTaskNo(taskNo);
        // 修改状态
        _Task.UpdateTaskAndCmdStatusForManualEnd(taskCmd.TargetLoc.GetValueOrDefault(), taskId, (int)EnumTaskStatus.Finish);
        // 备份删除
        _Task.BakAndDeleteTaskAndCmd(taskId);
        // 修改货位标识
        _RcsLocation.UpdateLocationAndWcsLocWithSkuId(task.SkuId, task.CurrentLoc, task.TargetLoc, true);
        return 1;
    }
    // Ems任务完成
    public int EmsTaskFinish(POWcsTask task)
    {
        WriteLog($"人工完成{task.TaskNo},211", true);
        var taskId = task?.Id ?? 0;
        var taskNo = task?.TaskNo ?? 0;
        var taskCmd = _TaskCmd.GetExecutedTaskCmdByTaskNo(taskNo);
        WriteLog($"人工完成{task.TaskNo},212", true);
        // 获取ems 位置
        var equipId = taskCmd?.EquipId ?? 0;
        var startLoc = _WcsEquipLoc.GetLocIdByEquipId(equipId);
        WriteLog($"人工完成{task.TaskNo},213", true);
        // 获取 skuID
        if (task?.SkuId is not long skuId)
        {
            WriteLog($"人工完成{task.TaskNo},214", true);
            return 0;
        }
        WriteLog($"人工完成{task.TaskNo},215", true);
        var summary = _WmsOutOrderSummary.GetOutOrderSummaryById(task.SummaryId ?? 0);
        // 出库单完成-备份
        _WmsOutOrderMaster.OutOrderFinish(task);
        WriteLog($"人工完成{task.TaskNo},216", true);
        // 修改货位标识
        var targetLoc = taskCmd.TargetLoc.GetValueOrDefault();
        WriteLog($"人工完成{task.TaskNo},217", true);
        _RcsLocation.UpdateLocationAndWcsLocWithSkuId(skuId, startLoc, targetLoc);
        WriteLog($"人工完成{task.TaskNo},218", true);
        // 修改状态
        _Task.UpdateTaskAndCmdStatusForManualEnd(targetLoc, taskId, (int)EnumTaskCmdStatus.Finish);
        WriteLog($"人工完成{task.TaskNo},219", true);
        // 备份删除
        _Task.BakAndDeleteTaskAndCmd(taskId);
        WriteLog($"人工完成{task.TaskNo},220", true);

        // 同步MES
        try
        {
            WriteLog($"任务{taskNo}开始同步出库mes", true);
            if (task.TaskType != (int)EnumTaskType.EmsEmpty)
            {
                SyncMes(skuId, summary, targetLoc);
            }
        }
        catch (Exception ex)
        {
            WriteLog($"任务{taskNo}同步出库mes异常,{ex.ToString()}", true);
        }



        return 1;
    }
    // 异常任务完成 [完成删除任务、指令、删除绑定]
    public int Abnormal(POWcsTask task)
    {
        return TransportationTaskFinish(task);
    }
    #endregion

    public int DelTask(string productCode)
    {
        var result = 0;
        TaskOperParm taskOperParm = new TaskOperParm();
        var taskNo = _Task.DelTaskIdByProductCode(productCode);

        if (taskNo > 0)
        {
            taskOperParm.TaskNo = taskNo;
            result = DeleteTask(taskOperParm, -1, "0", "0");
        };
        return result;
    }
    #region 任务删除

    [OperationLog("任务删除")]
    public int DeleteTask(TaskOperParm parm, long userId, string userName, string clientHost)
    {
        var task = _Task.GetTaskByTaskNo(parm.TaskNo);
        var IsDisable = parm.IsDisable ?? 1;
        if (task == null) return 0;
        var result = 0;
        var remark = userId != -1 ? "【手工删除】" : "【PDA删除】";
        _Task.UpdateTaskReamrkByTaskId(task.Id.GetValueOrDefault(), $"{remark}{task.RemarkMemo}");
        switch (task.TaskType)
        {
            case (int)EnumTaskType.Warehousing:
                result = DeleteTaskWarehous(task, IsDisable);
                break;
            case (int)EnumTaskType.Exwarehouse:
                result = DeleteTaskExWarehous(task, IsDisable);
                break;
            case (int)EnumTaskType.Abnormal:
                result = DeleteAbnormal(task);
                break;
            case (int)EnumTaskType.Transportation:
                result = DeleteTaskTransportation(task);
                break;
            case (int)EnumTaskType.EMS:
                result = DeleteTaskEms(task);
                break;
            default:
                result = DeleteAbnormal(task);
                break;
        }
        return result;
    }
    // 线体任务删除
    public int DeleteTaskTransportation(POWcsTask task)
    {

        if (task == null) return 1;
        var result = _Task.BakAndDeleteTaskAndCmd(task.Id.GetValueOrDefault());
        _WcsScanner.DeleWcsScannerByTaskId(task.Id ?? 0, "任务删除时自动删除");
        return result;
    }
    // 入库任务删除
    public int DeleteTaskWarehous(POWcsTask task, int IsDisable)
    {

        if (task == null) return 1;
        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(task.Id.GetValueOrDefault());

        var locType = _RcsLocation.GetLocationTypeById(task.TargetLoc.GetValueOrDefault());
        if (locType == (int)EnumLocType.Location && IsDisable == 1)
        {
            if (taskCmd?.TaskType == (int)EnumTaskType.Warehousing)
            {
                _RcsLocation.UpdateLocUnEnable(task.TargetLoc.GetValueOrDefault(), task.TaskNo.GetValueOrDefault());
            }
        }

        var result = _Task.BakAndDeleteTaskAndCmd(task.Id.GetValueOrDefault());
        _WcsScanner.DeleWcsScannerByTaskId(task.Id ?? 0, "任务删除时自动删除");
        return result;
    }
    // 出库任务删除
    public int DeleteTaskExWarehous(POWcsTask task, int IsDisable)
    {

        if (task == null) return 1;
        var result = 0;
        var taskCmd = _TaskCmd.GetTaskCmdByTaskId(task.Id.GetValueOrDefault());
        var locType = _RcsLocation.GetLocationTypeById(task.StartLoc.GetValueOrDefault());
        if (locType == (int)EnumLocType.Location && IsDisable == 1)
        {
            if (taskCmd?.CmdType == (int)EnumTaskType.Exwarehouse)
            {
                _RcsLocation.UpdateLocUnEnable(task.StartLoc.GetValueOrDefault(), task.TaskNo.GetValueOrDefault());
            }
        }
        try
        {
            //备份并删除出库单

            var orders = _WmsOutOrderMaster.BakAndDeleteOutOrderByTask(task);

            //备份并删除任务
            result = _Task.BakAndDeleteTaskAndCmd(task.Id.GetValueOrDefault());
            _WcsScanner.DeleWcsScannerByTaskId(task.Id ?? 0, "任务删除时自动删除");
        }
        catch (Exception ex)
        {
            WriteLog($"手动删除出库任务异常{ex.ToString()}", true);
        }
        return result;
    }
    // Ems 任务删除
    public int DeleteTaskEms(POWcsTask task)
    {

        if (task == null) return 1;
        var result = 0;

        //出库和EMS任务需要还原出库订单
        // _WmsOutOrderSummary.ReRequestSummary(task.SummaryId.GetValueOrDefault());
        try
        {
            //备份并删除出库单
            var orders = _WmsOutOrderMaster.BakAndDeleteOutOrderByTask(task);

            result = _Task.BakAndDeleteTaskAndCmd(task.Id ?? 0);
            _WcsScanner.DeleWcsScannerByTaskId(task.Id ?? 0, "任务删除时自动删除");
        }
        catch (Exception ex)
        {
            WriteLog($"手动删除ems任务异常{ex.ToString()}", true);
        }
        return result;
    }
    // 异常任务删除
    public int DeleteAbnormal(POWcsTask task)
    {
        if (task == null) return 1;
        var result = 0;
        try
        {
            result = _Task.BakAndDeleteTaskAndCmd(task.Id ?? 0);
            _WcsScanner.DeleWcsScannerByTaskId(task.Id ?? 0, "任务删除时自动删除");
        }
        catch (Exception ex)
        {
            WriteLog($"手动删除异常任务异常{ex.ToString()}", true);
        }
        return result;
    }
    #endregion


    [OperationLog("指令删除")]
    public int DeleteTaskCmd(TaskOperParm parm)
    {
        var task = _Task.GetTaskByTaskNo(parm.TaskNo);
        if (task == null) return 0;
        _TaskCmd.UpdateTaskCmdReamrkByTaskId(task.Id.GetValueOrDefault(), $"【手工删除】{task.RemarkMemo}");
        //备份为人工完成并删除
        return _TaskCmd.BakAndDeleteCmd(task.Id.GetValueOrDefault());
    }

    [OperationLog("指令重下")]
    public int SendAgainTaskCmd(TaskOperParm parm)
    {
        var result = 0;
        try
        {
            WriteLog($"任务号{parm.TaskNo},指令重下11", true);
            var task = _Task.GetTaskByTaskNo(parm.TaskNo);
            if (task == null) return 0;
            WriteLog($"任务号{parm.TaskNo},指令重下22", true);
            var taskCmdList = _TaskCmd.GetTaskCmdsByGroupNo((int)task.TaskGroup);
            if (taskCmdList == null)
            { return 0; }
            WriteLog($"任务号{parm.TaskNo},指令重下33", true);
            WriteLog($"任务号{parm.TaskNo},指令重下shu1--{taskCmdList.ToJson()}");

            var count = taskCmdList.Select(t => t.CmdType).Distinct().Count();
            WriteLog($"任务号{parm.TaskNo},指令重下shu2--{count}");
            if (count != 1)
            {
                return 0;
            }
            WriteLog($"任务号{parm.TaskNo},指令重下44", true);
            _TaskCmd.UpdateTaskCmdReamrkByTaskId(task.Id.GetValueOrDefault(), $"【指令重下】{task.RemarkMemo}");
            WriteLog($"任务号{parm.TaskNo},指令重下55", true);
            //备份为人工完成并删除
            result = _TaskCmd.ReSendTaskCmd(taskCmdList);
            WriteLog($"任务号{parm.TaskNo},指令重下66", true);
        }
        catch (Exception ex)
        {
            WriteLog($"任务号{parm.TaskNo},指令重下异常{ex.ToString()}", true);
        }

        return result;

    }

    //[OperationLog("指令重下")]
    //public int SendAgainTaskCmd(TaskOperParm parm, long userId, string userName, string clientHost)
    //{
    //    var task = _Task.GetTaskByTaskNo(parm.TaskNo);
    //    if (task == null) return 0;
    //    var taskCmdList = _TaskCmd.GetTaskCmdsByGroupNo((int)task.TaskGroup);
    //    if (taskCmdList == null) return 0;
    //    //备份为人工完成并删除
    //    var result = _TaskCmd.ReSendTaskCmd(taskCmdList);
    //    return result;
    //}



    [OperationLog("指令完成")]
    public int FinishTaskCmd(TaskOperParm parm)
    {
        var task = _Task.GetTaskByTaskNo(parm.TaskNo);
        if (task == null) return 0;
        var taskCmd = _TaskCmd.GetTaskCmdByTaskNo(parm.TaskNo);
        if (taskCmd == null) return 0;

        _TaskCmd.UpdateTaskCmdReamrkByTaskId(task.Id ?? 0, $"【指令完成】{task.RemarkMemo}");
        //备份为人工完成并删除
        var result = _WcsLocSku.SetWcsLocSku(taskCmd?.TargetLoc ?? 0, task?.SkuId ?? 0, true);
        if (result > 0)
        {
            // 删除绑定
            if (taskCmd.CmdType == (int)EnumTaskType.Warehousing)
            {
                // 入库
                _Task.UpdateTaskAndCmdStatusForManualEnd(task.TargetLoc ?? 0, task.Id ?? 0, (int)EnumTaskStatus.Finish);
                result = _Task.BakAndDeleteTask(task.Id.GetValueOrDefault());
                return result;
            }

            _TaskCmd.UpdateTaskCmdStatusForManualEnd(taskCmd.TargetLoc ?? 0, task.Id ?? 0, (int)EnumTaskStatus.Finish);
            result = _TaskCmd.BakAndDeleteCmd(task.Id.GetValueOrDefault());
            if (taskCmd.CmdType == (int)EnumTaskType.Exwarehouse)
            {
                var skuId = task.SkuId.GetValueOrDefault();
                var startLoc = taskCmd.StartLoc.GetValueOrDefault();
                var targetLoc = taskCmd.TargetLoc.GetValueOrDefault();
                // 修改货位标识
                _RcsLocation.UpdateLocationAndWcsLocWithSkuId(skuId, startLoc, targetLoc, true);
                // 出库
                FinishTaskExWarehouse(taskCmd, task.TargetLoc.GetValueOrDefault());
            }

        }
        return result;
    }


    private int? FinishTaskExWarehouse(POWcsTaskCmd taskCmd, long targetLoc)
    {
        //出库完成生成一条新的线体指令

        var netPut = _WcsAsrsNetOutPut.GetFirstAsrsNetOutputByTargetLoc(targetLoc);
        var equipLoc = _WcsEquipLoc.GetEquipLocByLocId(taskCmd.TargetLoc.GetValueOrDefault());
        var tranLoc = netPut.TranLoc.GetValueOrDefault();
        var inCuring = _WcsNetInCuring.GetWcsNetinCuringByTranLoc(tranLoc);
        var ntaskCmd = new POWcsTaskCmd()
        {
            TaskId = taskCmd.TaskId,
            TaskNo = taskCmd.TaskNo,
            TaskType = (int)EnumTaskType.Exwarehouse,
            EquipId = equipLoc?.EquipId,
            StartLoc = taskCmd.TargetLoc,
            CurrentLoc = taskCmd.TargetLoc,
            TargetLoc = inCuring?.ScannerLoc,
            CmdStatus = (int)EnumTaskCmdStatus.Executable,
            FinishMode = (int)EnumFinishMode.NotFinished,
            CreateTime = DateTime.Now,
            UpdateTime = DateTime.Now,
            UseFlag = 1,
            CmdType = (int)EnumTaskType.Transportation,
            IsSpray = taskCmd.IsSpray,
            SpinAngle = taskCmd.SpinAngle,
            PairWait = taskCmd.PairWait
        };
        var cmd = _TaskCmd.CreateTaskCmd(ntaskCmd);
        return cmd?.TaskNo;
    }
    public List<TaskCmdBean> GetTaskCmdList(TaskParm parm)
    {
        var taskCmdList = _TaskCmd.GetTaskCmds();
        var taskType = 0;
        if (!string.IsNullOrWhiteSpace(parm.TaskType))
        {
            taskType = Convert.ToInt32(parm.TaskType);
        }

        var taskList = _Task.GetTaskByType(taskType);
        var taskNo = 0;
        if (!string.IsNullOrWhiteSpace(parm.TaskNo))
        {
            taskNo = Convert.ToInt32(parm.TaskNo);
        }
        if (taskNo != 0)
        {
            taskCmdList = taskCmdList.Where(t => t.TaskNo == taskNo).ToList();
        }
        if (taskType != 0)
        {
            taskCmdList = taskCmdList.Where(t => t.TaskType == taskType).ToList();
        }
        var equipList = _RcsEquip.GetEquips();
        var result = taskCmdList.Join(equipList, f => f.EquipId, s => s.Id, (f, s) => new TaskCmdBean
        {
            TaskCmdId = f.TaskId.GetValueOrDefault(),
            CreateTime = f.CreateTime.GetValueOrDefault(),
            CurrentLoc = f.CurrentLoc.GetValueOrDefault(),
            EquipName = s.EquipName,
            StartLoc = f.StartLoc.GetValueOrDefault(),
            TargetLoc = f.TargetLoc.GetValueOrDefault(),
            TaskNo = f.TaskNo.GetValueOrDefault(),
            CmdStatus = f.CmdStatus.GetValueOrDefault(),
            TaskType = f.TaskType.GetValueOrDefault(),
            SpinAngle = f.SpinAngle.GetValueOrDefault(),
            Isspray = f.IsSpray.GetValueOrDefault()
        }
        ).ToList();
        result.ForEach(f =>
        {
            switch (f.TaskType)
            {
                case (int)EnumTaskType.Warehousing:
                    f.TaskTypeDesc = "入库任务";
                    break;
                case (int)EnumTaskType.Exwarehouse:
                    f.TaskTypeDesc = "出库任务";
                    break;
                case (int)EnumTaskType.Transportation:
                    f.TaskTypeDesc = "输送线任务";
                    break;
                case (int)EnumTaskType.Rotate:
                    f.TaskTypeDesc = "旋转任务";
                    break;
                case (int)EnumTaskType.EMS:
                    f.TaskTypeDesc = "EMS任务";
                    break;
                //case (int)EnumTaskType.TransferLibrary:
                //    f.TaskTypeDesc = "移库任务";
                //    break;
                default:
                    f.TaskTypeDesc = "异常任务";
                    break;
            }
            switch (f.CmdStatus)
            {
                case (int)EnumTaskCmdStatus.Create:
                    f.CmdStatusDesc = "创建";
                    break;
                case (int)EnumTaskCmdStatus.Executable:
                    f.CmdStatusDesc = "可下发";
                    break;
                case (int)EnumTaskCmdStatus.Executed:
                    f.CmdStatusDesc = "已下发";
                    break;
                default:
                    f.CmdStatusDesc = "指令完成";
                    break;
            }
        });
        return result;
    }

    public List<Spi.TaskStatus> GetTaskStatus()
    {
        return _Task.GetTaskStatus();
    }

    public TaskException GetTaskException(string ProductCode)
    {
        var skuId = _ProdProduct.GetSkuIdByCode(ProductCode);
        var bakTask = _BakWcsTask.GetBakTaskBySkuIdAndType(skuId, (int)EnumTaskType.Abnormal);
        if (bakTask is null)
        {
            return new() { Message = $"线体扫描条码可能为:NOREAD,无法找到异常信息" };
        }

        return new() { TaskFalg = 1, Message = $"{bakTask.RemarkMemo}" };
    }

    /// <summary>
    /// 绑定入库
    /// </summary>
    /// <param name="pdaInParam"></param>
    /// <returns>
    /// 空：成功
    /// 非空：异常（前端显示返回内容）
    /// </returns>
    public string AddPDATask(PdaInParam pdaInParam)
    {
        var crnId = pdaInParam?.CrnId ?? 0;
        var productCode1 = pdaInParam?.ProductCode1;
        var productCode2 = pdaInParam?.ProductCode2;
        var productCodes = new List<string>();


        var crnFlag = _RcsEquip.IsEnableEquipById(crnId);
        if (!crnFlag)
        {
            return $"堆垛机异常";
        }


        var wcsAsrsCrnAbnormalInput = _WcsAsrsCrnAbnormalInput.GetAsrsCrnAbnormalInPutByCrnId(crnId);
        if (wcsAsrsCrnAbnormalInput is null)
        {
            return $"立库人工入库放胎位未维护";
        }
        var location1 = wcsAsrsCrnAbnormalInput.InputLoc1.GetValueOrDefault();
        var location2 = wcsAsrsCrnAbnormalInput.InputLoc2.GetValueOrDefault();

        var result = string.Empty;
        var materialId1 = 0L;
        var materialId2 = 0L;

        if (!string.IsNullOrWhiteSpace(productCode1))
        {
            (result, materialId1) = CheckProductCode(productCode1, location1);
            if (!string.IsNullOrWhiteSpace(result))
            {
                return result;
            }
            productCodes.Add(productCode1);
        }

        if (!string.IsNullOrWhiteSpace(productCode2))
        {
            (result, materialId2) = CheckProductCode(productCode2, location2);
            if (!string.IsNullOrWhiteSpace(result))
            {
                return result;
            }
            productCodes.Add(productCode2);
        }
        if (productCodes.Count == 0)
        {
            return $"未找到绑定条码";
        }
        if (materialId1 != 0)
        {
            _RcsLocation.UpdateInLocationHasGood(materialId1, location1, productCode1);
        }
        if (materialId2 != 0)
        {
            _RcsLocation.UpdateInLocationHasGood(materialId2, location2, productCode2);
        }

        return result;
    }

    public string AddAbnormalPdaTask(PdaAbnormalInParam pdaAbnormalInParam)
    {
        if (pdaAbnormalInParam is null)
        {
            return $"缺少参数";
        }
        if (string.IsNullOrWhiteSpace(pdaAbnormalInParam.ProductCode))
        {
            return $"缺少条码";
        }

        var locs = _RcsLocation.GetLocationByType((int)EnumCodeEquipType.AbnormalInLoc);
        if (locs.Count == 0)
        {
            return $"异常入库口未找到{(int)EnumCodeEquipType.AbnormalInLoc}";
        }

        var productCode = pdaAbnormalInParam.ProductCode;
        var abnoramlLoc = locs.FirstOrDefault().Id ?? 0;

        var product = _MesProduct.GetInfoByBarcode(productCode);
        if (product is null)
        {
            return $"条码{productCode}不存在";
        }

        // 判断任务是否创建
        var task = _Task.GetTaskByProductCode(productCode);
        if (task is not null)
        {
            var startLoc = task.StartLoc ?? 0;
            var taskId = task.Id ?? 0;
            var remark = task.RemarkMemo;
            if (startLoc != abnoramlLoc)
            {
                _Task.UpdateTaskReamrkByTaskId(taskId, $"【PDA异常入库删除】{remark}");
                _Task.BakAndDeleteTaskAndCmd(taskId);
            }
            else
            {
                return $"任务已创建，任务流水号{(int)EnumCodeEquipType.AbnormalInLoc}";
            }
        }

        var location = _RcsLocation.GetLocationById(abnoramlLoc);
        if (location is null)
        {
            return $"{abnoramlLoc}不存在";
        }
        if (location.ProductCode == productCode && location.TaskOccupy == 0)
        {
            return $"{productCode}已绑定位置";
        }

        // 修改条码
        var result = _RcsLocation.UpdateLocProductCode(abnoramlLoc, productCode);
        if (result == 0)
        {
            return $"{productCode}绑定失败";
        }
        return $"绑定成功";
    }

    /// <summary>
    /// 同步MES
    /// </summary>
    /// <param name="skuId"></param>
    /// <param name="summaryId"></param>
    /// <param name="targetLoc"></param>
    private void SyncMes(long skuId, POWmsOutOrderSummary summary, long targetLoc)
    {
        WriteLog($"ems完成开始推送信息skuId-{skuId},summary{summary?.Id},targetloc{targetLoc}", true);
        var tireBarcode = _ProdProduct.GetCodeBySkuId(skuId);
        //WriteLog($"ems完成开始推送信息tireBarcode-{tireBarcode}", true);
        var curingRL = _RcsEquipCuring.GetCuringRLByCuringLocId(targetLoc);
        var equipNo = curingRL?.CuringCode;
        var model = curingRL?.Mode;
        //var equipModel = _RcsEquipCuring.GetCuringRLByMesModelRL(model);
        //var summmary = _WmsOutOrderSummary.GetOutOrderSummaryById(summaryId);
        var material = _ProdMaterial.GetMaterialById(summary?.MaterialId ?? 0);
        //    if (summary.CrnId == 10030901 || summary.CrnId == 10031001 || summary.CrnId == 10031101 || summary.CrnId == 10031201
        //|| summary.CrnId == 10031301 || summary.CrnId == 10031401 || summary.CrnId == 10031501 || summary.CrnId == 10031601)
        //    {
        //        if (model == "L")
        //        {
        //            model = "R";
        //        }
        //        else
        //        {
        //            model = "L";
        //        }
        //    }


        var mesService = K8.RSF.Client.Create<IMesService>();
        EndParam param = new EndParam()
        {
            TcmNo = equipNo,
            TcmDir = model,
            TcmSpec = material?.MaterialCode,
            TcmSpecDesc = material?.MaterialCode,
            TirCode = tireBarcode,
            Angle = 0,
            TbmPs = summary.TbmPs ?? "",
            CompFlag = "E",
            //TbmSpec=mesproduct?.TbmSpec
        };
        mesService.AddOutEnd(param);

    }
    public string Query(string locName, string taskNo, string spec, string OrderByType, string OrderByName, string productCode)
    {
        DbHelper dbHelper = new DbHelper();
        StringBuilder sql = new StringBuilder();

        sql.Append(@"select a.objid TaskId,
          ot.product_code ProductCode,
          a.sku_id  SkuId,
          a.task_no TaskNo,
          b.objid OrderId,
          b.plan_count PlanCount,
          b.real_count RealCount,
          b.create_time CreateTime,
          ra.loc_name OutLocName,
          ra2.loc_name TargetLocName ,
          rb.loc_name OrderLocName,
          c.spec Spec,
          rd.loc_name CurrentName,
          ( CASE d.cmd_status WHEN '2' THEN '已下发' ELSE '未下发' END ) AS CmdStatus ,
          b.remark_memo RemarkMemo 
        FROM
          wcs_task a
          LEFT JOIN wms_out_order_summary b ON a.summary_id= b.objid
          LEFT JOIN prod_material c ON b.material_id= c.objid
          LEFT JOIN wcs_task_cmd d ON a.objid= d.task_id
          LEFT JOIN rcs_location ra ON a.start_loc= ra.objid
          LEFT JOIN rcs_location ra2 ON a.target_loc= ra2.objid
          LEFT JOIN rcs_location rb ON b.target_loc= rb.objid
          LEFT JOIN rcs_location rd ON d.target_loc= rd.objid
          LEFT JOIN prod_sku_product sk ON a.sku_id= sk.sku_id
          LEFT JOIN prod_product ot ON sk.product_id= ot.objid 
        WHERE
          a.summary_id !=0 ");
        //and rb.loc_name like '0%' and a.task_no = 1 and c.spec = '2'

        if (!String.IsNullOrWhiteSpace(locName))
        {
            sql.Append($" and rb.loc_name like '%{locName}%'");
        }
        if (!String.IsNullOrWhiteSpace(taskNo))
        {
            sql.Append($" and a.task_no = '{taskNo}'");
        }
        if (!String.IsNullOrWhiteSpace(spec))
        {
            sql.Append($" and c.spec like '%{spec}%'");
        }
        if (!String.IsNullOrWhiteSpace(productCode))
        {
            sql.Append($" and ot.product_code like '%{productCode}%'");
        }


        if (!string.IsNullOrWhiteSpace(OrderByName))
        {
            if (OrderByType == "ASC")
            {
                sql.Append($" order by {OrderByName} asc");
            }
            else
            {
                sql.Append($" order by {OrderByName} desc");
            }
        }
        else
        {
            sql.Append($" order by d.update_time");
        }

        dbHelper.CommandText = sql.ToString();
        WriteLog($"订单追踪2-{sql}", true);
        dbHelper.CommandType = System.Data.CommandType.Text;

        var r = dbHelper.GetXDataTable();
        if (r is null || r.DataTable is null || r.DataTable.Rows is null || r.DataTable.Rows.Count <= 0) return "";
        return r.Rows.ToJson();
    }

    //public List<POCruingAsrsMonitor> QueryCruingAsrsMonitor(CuringMonitorParm parm)
    //{
    //    var service = K8.RSF.Client.Create<MexicoSailunMES.Spi.IMiddleMesService>();
    //    var data = service.QueryMonitor();
    //    //.Where(s => s.IsEnableRequest == 1)
    //    //.Where(s => s.IsEnablePush == 1)
    //    //.Where(s => s.EquipStatusMes == 1)
    //    //.Where(s => s.EquipStatusHost == 1)
    //    //.Where(s => s.PlanCuringCount > s.RealCuringCount);

    //    if (!String.IsNullOrEmpty(parm.no))
    //    {
    //        data = data.Where(s => s.EquipNo == parm.no).ToList();
    //    }
    //    if (!String.IsNullOrEmpty(parm.isEnableRequest))
    //    {
    //        data = data.Where(s => s.IsEnableRequest == int.Parse(parm.isEnableRequest)).ToList();
    //    }
    //    if (!String.IsNullOrEmpty(parm.isEnablePush.ToString()))
    //    {
    //        data = data.Where(s => s.IsEnablePush == int.Parse(parm.isEnablePush)).ToList();
    //    }
    //    if (!String.IsNullOrEmpty(parm.equipStatusMes.ToString()))
    //    {
    //        data = data.Where(s => s.EquipStatusMes == int.Parse(parm.equipStatusMes)).ToList();
    //    }
    //    if (!String.IsNullOrEmpty(parm.equipStatusHost.ToString()))
    //    {
    //        data = data.Where(s => s.EquipStatusHost == int.Parse(parm.equipStatusHost)).ToList();
    //    }
    //    if (!String.IsNullOrEmpty(parm.hostWmsFlag.ToString()))
    //    {
    //        data = data.Where(s => s.HostWmsFlag == int.Parse(parm.hostWmsFlag)).ToList();
    //    }
    //    if (!String.IsNullOrEmpty(parm.mesWmsFlag.ToString()))
    //    {
    //        data = data.Where(s => s.MesWmsFlag == int.Parse(parm.mesWmsFlag)).ToList();
    //    }

    //    return data.ToList();
    //}

    public bool DeleteOutOrder(long master_id)
    {

        var db = MexicoSailunMDC.Dao.Db.Default;

        db.WmsOutOrderMasters.Where(s => s.Id == master_id).Delete();
        db.WmsOutOrderSummarys.Where(s => s.MasterId == master_id).Delete();

        try
        {
            var wmsOutOrderMaster = db.WmsOutOrderMasters.Where(s => s.Id == master_id).First();
            wmsOutOrderMaster.RemarkMemo = "人工删除";
            db.BakWmsOutOrderMasters.CopyFrom(wmsOutOrderMaster);

            var wmsOutOrderSummary = db.WmsOutOrderSummarys.Where(s => s.MasterId == master_id).ToList();
            foreach (var item in wmsOutOrderSummary)
            {
                item.RemarkMemo = "人工删除";
                db.BakWmsOutOrderMasters.CopyFrom(item);
            }

        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }



    private (string, long) CheckProductCode(string productCode, long locId)
    {
        // 胎胚信息
        var product = _ProdProduct.GetProductBindingInfoByCode(productCode);
        if (product is null)
        {
            return ($"条码{productCode}未找到胎胚信息", 0);
        }
        // 任务是否创建
        var task = _Task.GetTaskBySkuId(product.POProdSku.Id.GetValueOrDefault());
        if (task is not null)
        {
            return ($"条码{productCode}任务已创建常", 0);
        }

        // 绑定位置
        var location = _RcsLocation.GetLocationById(locId);
        if (location.LocEnable == 0)
        {
            return ($"条码{productCode}绑定位置{locId}异常", 0);
        }

        // 是否已经绑定
        if (productCode.Equals(location.ProductCode))
        {
            return ($"条码{productCode}已绑定位置{locId}", 0);
        }
        return (string.Empty, product.POProdMaterial.Id.GetValueOrDefault());
    }


    public List<AbnormalBean> GetAbnormalList(AbnormalParm parm)
    {
        var barCode = parm?.BarCode ?? "";
        var result = _BakWcsTask.GetAbnormalTask(barCode);
        return result;
    }
}
